import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_roujiaosuo/constants/home_constant.dart';
import 'package:flutter_roujiaosuo/flutter_bloc/bloc/home_bloc.dart';
import 'package:flutter_roujiaosuo/flutter_bloc/bloc/home_event.dart';
import 'package:flutter_roujiaosuo/flutter_bloc/bloc/home_state.dart';
import 'package:flutter_roujiaosuo/flutter_bloc/requests/api/home_api.dart';
import 'package:flutter_roujiaosuo/flutter_bloc/requests/repository/home_repository.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_roujiaosuo/ui/components/banner1.dart';
import 'package:flutter_roujiaosuo/ui/components/dotsIndicator.dart';
import 'package:flutter_roujiaosuo/ui/components/home/home_listItem.dart';
import 'package:flutter_roujiaosuo/ui/components/home/navBar.dart';
import 'package:flutter_roujiaosuo/ui/components/net_progress.dart';
import 'package:flutter_roujiaosuo/ui/supply_list.dart';
import './detail.dart';
import './login.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   title: Text('肉交所'),
      // ),
      body: HomeView(),
    );
  }
}

class HomeView extends StatefulWidget {
  HomeView({Key key}) : super(key: key);

  _HomeViewState createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {
  ScrollController controller = ScrollController(initialScrollOffset: 0.0);
  int _homeMeumIndex = 0;
   HomeBloc homeBloc;
  @override
  void initState() {
    // TODO: implement initState
    controller.addListener(() {
      // bloc.scrollLister(controller.offset);
      print(controller.offset);
      homeBloc.dispatch(HomeScrollViewOffsetEvent(scrollOffset:controller.offset));

    });
    homeBloc = HomeBloc(homeRepository: HomeRepository(homeApi: HomeApi()));
          homeBloc.dispatch(FetchHomeTopDataEvent());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
          controller: controller,
          physics: const AlwaysScrollableScrollPhysics(),
          slivers: <Widget>[
            // SliverSafeArea(
            //   sliver: ,
            // )

            SliverAppBar(
              expandedHeight: 160,
              // title: Text('肉交所'),
              // floating: true,
              elevation: 0.0,
              pinned: true,
              flexibleSpace: BannerView(),
            ),
            SliverList(
                delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
              return [
                SizedBox(
                  height: 160,
                  child: PageView.builder(
                    itemBuilder: (context, position) {
                      return [HomeMeums(), HomeMeums()][_homeMeumIndex];
                    },
                    itemCount: 2,
                    onPageChanged: (index) {
                      setState(() {
                        _homeMeumIndex = index;
                      });
                    },
                  ),
                ),
                SizedBox(
                  height: 10,
                  child: Container(
                    color: Colors.grey[100],
                  ),
                )
              ][index];
            }, childCount: 2)),
            SliverFixedExtentList(
              itemExtent: 240.0,
              delegate: new SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                //创建列表项
                return HomeListItem();
              }, childCount: 50 //50个列表项
                  ),
            ),
          ],
        );
  }
}

class BannerView extends StatefulWidget {
  @override
  _BannerViewState createState() => _BannerViewState();
}

class _BannerViewState extends State<BannerView> {
  double opacityMethod(snapshot) {
    return snapshot.data == null || snapshot.data > 105
        ? 1
        : snapshot.data <= 0 ? 0 : snapshot.data / 105;
  }

  List<Widget> _buildBannerImage(bannerList) {
    List<Widget> list = new List<Widget>();
    for (var item in bannerList) {
      list.add(BlocBuilder(
        bloc: homeBloc,
        builder: (BuildContext context, MyState state) {
          return Container();
        },
      )
        StreamBuilder(
          stream: bloc.scrollStream,
          initialData: 0,
          builder: (context, AsyncSnapshot snapshot) {
            return Stack(
              fit: StackFit.expand,
              children: <Widget>[
                Image.network(
                  item.thumb,
                  // color: Colors.green.withOpacity(snapshot.data==null?1:snapshot.data / 200),
                  fit: BoxFit.cover,
                ),
              ],
            );
          }));
    }
    // bannerList.map((item) {
    // });
    return list;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    // final HomeBloc bloc = BlocProvider.of<HomeBloc>(context);
    
    return BlocBuilder(
      bloc: homeBloc,
      builder: (BuildContext context, HomeState state) {
        if (state is LoadingHomeState) {
          return RefreshProgressView();
        }
        if(state is LoadedHomeState){
          if (state.homeTopModel.data.code != '200') {
          return Center(
            child: Text('loading'),
          );
        } else {
          var bannerList = state.homeTopModel.bannerModelList;
          return Stack(children: <Widget>[
            new Swiper(
              autoplay: true,
              itemCount: _buildBannerImage(bannerList).length,
              itemBuilder: (context, index) {
                return _buildBannerImage(bannerList)[index];
              },
              pagination: new SwiperPagination(),
              control: new SwiperControl(),
            ),
            Positioned(
                    height: 100,
                    top: 0,
                    left: 0,
                    right: 0,
                    child: HomeNavBar(
                        actions: <Widget>[
                          IconButton(
                            icon: Icon(Icons.ac_unit),
                            onPressed: () {
                              Navigator.push(context,
                                  MaterialPageRoute(builder: (contxt) {
                                return LoginView();
                              }));
                            },
                          )
                        ],
                        title: ConstrainedBox(
                          constraints:
                              BoxConstraints(minWidth: 100, maxWidth: 200),
                          child: Container(
                            color: Colors.black,
                          ),
                        ),
                        leading: SizedBox.expand(
                          child: Row(
                            children: <Widget>[
                              IconButton(
                                icon: Icon(Icons.add),
                                onPressed: () {},
                              ),
                              Text('请选择位置'),
                              Expanded(
                                child: Text(
                                  '请选择位置',
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          ),
                        ),
                        gradientStart:
                            Colors.green.withOpacity(opacityMethod(snapshot)),
                        gradientEnd: Colors.blueAccent
                            .withOpacity(opacityMethod(snapshot)),
                        backgroundColor: Theme.of(context)
                            .backgroundColor
                            .withOpacity(opacityMethod(snapshot))),
                  )
            // BannerWidget(
            //   data: _buildBannerImage(bannerList),
            //   height: 210,
            // ),
            // StreamBuilder<Object>(
            //     stream: bloc.scrollStream,
            //     initialData: 0,
            //     builder: (context, snapshot) {
            //       return 
            //     })
          ]);
        }
      },
        }
        return Container();
      },
    )
    
     StreamBuilder(
      initialData: null,
      stream: bloc.topStream,
      builder: (context, AsyncSnapshot<HomeTopModel> snapshot) {
        
    );
  }
}

class HomeMeums extends StatelessWidget {
  const HomeMeums({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    PageController pageController = PageController(initialPage: 0);

    List<Widget> _buildPage(items) {
      List<Widget> list = new List<Widget>();
      for (var item in items) {
        list.add(HomeMeum(
          list: item,
        ));
      }
      return list;
    }

    return StreamBuilder(
        initialData: 0,
        stream: bloc.pageStream,
        builder: (context, snapshot) {
          return SizedBox(
              height: 140,
              child: Stack(
                children: <Widget>[
                  PageView(
                    controller: pageController,
                    children: _buildPage(homeMeums),
                  ),
                  Positioned(
                    bottom: 5,
                    left: 0,
                    right: 0,
                    child: DotsIndicator(
                      controller: pageController,
                      color: Theme.of(context).primaryColor,
                      unSelectColor: Colors.grey[600],
                      itemCount: homeMeums.length,
                    ),
                  )
                ],
              ));
        });
  }
}

class HomeMeum extends StatelessWidget {
  const HomeMeum({Key key, this.list}) : super(key: key);
  final List list;
  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    List<Widget> _buildItems(items) {
      List<Widget> list = new List<Widget>();
      for (var item in items) {
        list.add(Meum(
          title: item['title'],
          icon: item['icon'],
          width: width / 5,
        ));
      }
      return list;
      // return items
      //     .map((item) => Meum(
      //           title: item,
      //           width: width / 4,
      //         ))
      //     .toList();
    }

    // TODO: implement build
    return Wrap(
      children: _buildItems(list),
    );
  }
}

class Meum extends StatelessWidget {
  const Meum({Key key, this.width, this.title, this.icon, this.callback})
      : super(key: key);

  final double width;
  final Icon icon;
  final String title;
  final VoidCallback callback;
  @override
  Widget build(BuildContext context) {
    return Container(
      width: this.width,
      margin: EdgeInsets.only(top: 5),
      child: InkWell(
          onTap: () {
            Navigator.push(context,
                MaterialPageRoute(builder: (context) => SupplyListView()));
          },
          child: SizedBox(
            height: 65,
            child: Padding(
              padding: EdgeInsets.only(top: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[this.icon, Text('${this.title}')],
              ),
            ),
          )),
    );
  }
}
